﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.XmlDataProviderCore;
using MovieRental.DataInterfaces;
using MovieRental.Entities;
using MovieRental.GeneralDataExceptions;

namespace MovieRental.XmlRepositoryLibrary
{
    public class XmlMovieRepository : XmlRepository<MovieInfo>, IMovieRepository
    {
        public XmlMovieRepository(XmlDataProvider provider)
            : base(provider)
        {
        }

        public MovieInfo Load(Guid id)
        {
            using (var context = CreateContext())
            {
                var set = context.GetAllForType(typeof(MovieInfo)).Select(x => (MovieInfo)x);
                try
                {
                    return set.Single(x => x.Id == id);
                }
                catch (Exception ex)
                {
                    throw new ItemNotFoundException(id.ToString(), ex);
                }
            }
        }

        public void Delete(Guid id)
        {
            MovieInfo movie = new MovieInfo(id);
            Delete(movie);
        }

        public bool MovieExists(Guid id)
        {
            try
            {
                Load(id);
            }
            catch (ItemNotFoundException)
            {
                return false;
            }
            return true;
        }
    }
}
